axios
Promise based HTTP client for the browser and node.js
Features
- Make XMLHttpRequests from the browser
- Make http requests from node.js
- Supports the Promise API
- Intercept request and response
- Transform request and response data
- Automatic transforms for JSON data
- Client side support for protecting against XSRF
Browser Support
| | | | | |
---|
Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | 8+ ✔ |
Installing
Using cdn:
<script src="https://npmcdn.com/axios/dist/axios.min.js"></script>
Using npm:
$ npm install axios
Using bower:
$ bower install axios
Example
Performing a GET
request
axios.get('/user?ID=12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
Performing a POST
request
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
Performing multiple concurrent requests
function getUserAccount() {
return axios.get('/user/12345');
}
function getUserPermissions() {
return axios.get('/user/12345/permissions');
}
axios.all([getUserAccount(), getUserPermissions()])
.then(axios.spread(function (acct, perms) {
}));
axios API
Requests can be made by passing the relevant config to axios
.
axios(config)
axios({
method: 'post',
url: '/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
});
axios(url[, config])
axios('/user/12345');
Request method aliases
For convenience aliases have been provided for all supported request methods.
axios.request(config)
axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])
NOTE
When using the alias methods url
, method
, and data
properties don't need to be specified in config.
Concurrency
Helper functions for dealing with concurrent requests.
axios.all(iterable)
axios.spread(callback)
Creating an instance
You can create a new instance of axios with a custom config.
axios.create([config])
var instance = axios.create({
baseURL: 'https://some-domain.com/api/',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
});
Instance methods
The available instance methods are listed below. The specified config will be merged with the instance config.
axios#request(config)
axios#get(url[, config])
axios#delete(url[, config])
axios#head(url[, config])
axios#post(url[, data[, config]])
axios#put(url[, data[, config]])
axios#patch(url[, data[, config]])
Request Config
These are the available config options for making requests. Only the url
is required. Requests will default to GET
if method
is not specified.
{
url: '/user',
method: 'get',
baseURL: 'https://some-domain.com/api/',
transformRequest: [function (data) {
return data;
}],
transformResponse: [function (data) {
return data;
}],
headers: {'X-Requested-With': 'XMLHttpRequest'},
params: {
ID: 12345
},
paramsSerializer: function(params) {
return Qs.stringify(params, {arrayFormat: 'brackets'})
},
data: {
firstName: 'Fred'
},
timeout: 1000,
withCredentials: false,
adapter: function (config) {
},
auth: {
username: 'janedoe',
password: 's00pers3cret'
}
responseType: 'json',
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
progress: function (progressEvent) {
},
maxContentLength: 2000,
validateStatus: function (status) {
return status >= 200 && status < 300;
},
maxRedirects: 5
}
Response Schema
The response for a request contains the following information.
{
data: {},
status: 200,
statusText: 'OK',
headers: {},
config: {}
}
When using then
or catch
, you will receive the response as follows:
axios.get('/user/12345')
.then(function(response) {
console.log(response.data);
console.log(response.status);
console.log(response.statusText);
console.log(response.headers);
console.log(response.config);
});
Config Defaults
You can specify config defaults that will be applied to every request.
Global axios defaults
axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
Custom instance defaults
var instance = axios.create({
baseURL: 'https://api.example.com'
});
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
Config order of precedence
Config will be merged with an order of precedence. The order is library defaults found in lib/defaults.js
, then defaults
property of the instance, and finally config
argument for the request. The latter will take precedence over the former. Here's an example.
var instance = axios.create();
instance.defaults.timeout = 2500;
instance.get('/longRequest', {
timeout: 5000
});
Interceptors
You can intercept requests or responses before they are handled by then
or catch
.
axios.interceptors.request.use(function (config) {
return config;
}, function (error) {
return Promise.reject(error);
});
axios.interceptors.response.use(function (response) {
return response;
}, function (error) {
return Promise.reject(error);
});
If you may need to remove an interceptor later you can.
var myInterceptor = axios.interceptors.request.use(function () {});
axios.interceptors.request.eject(myInterceptor);
You can add interceptors to a custom instance of axios.
var instance = axios.create();
instance.interceptors.request.use(function () {});
Handling Errors
axios.get('/user/12345')
.catch(function (error) {
if (error.response) {
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else {
console.log('Error', error.message);
}
console.log(error.config);
});
You can define a custom HTTP status code error range using the validateStatus
config option.
axios.get('/user/12345', {
validateStatus: function (status) {
return status < 500;
}
})
Semver
Until axios reaches a 1.0
release, breaking changes will be released with a new minor version. For example 0.5.1
, and 0.5.4
will have the same API, but 0.6.0
will have breaking changes.
Promises
axios depends on a native ES6 Promise implementation to be supported.
If your environment doesn't support ES6 Promises, you can polyfill.
TypeScript
axios includes a TypeScript definition.
import * as axios from 'axios';
axios.get('/user?ID=12345');
Resources
Credits
axios is heavily inspired by the $http service provided in Angular. Ultimately axios is an effort to provide a standalone $http
-like service for use outside of Angular.
License
MIT